<template>
  <div ref="mapContainer" class="map-container">
    <div ref="map" class="map-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import chinaJson from '@/assets/city/000000.json';

export default {
  name: 'EnhancedChinaMap',
  props: {
    currentMapCode: {
      type: String,
      default: '000000'
    },
    currentMap: {
      type: String,
      default: 'china'
    },
    mapData: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'peoplecounting'
    },
  },
  data() {
    return {
      chart: null,
      resizeObserver: null,
      resizeDebounce: null,
      // 人数统计颜色分段（默认）
      baseColorPieces: [
        { gt: 400, label: '>400', color: '#FBC606' },          // 400 < x < +∞
        { gt: 350, lte: 400, label: '351-400', color: '#FBC606' },   // 350 < x ≤ 400
        { gt: 300, lte: 350, label: '301-350', color: '#FEF104' },   // 300 < x ≤ 350
        { gt: 250, lte: 300, label: '251-300', color: '#8FC320' },   // 250 < x ≤ 300
        { gt: 200, lte: 250, label: '201-250', color: '#009B44' },   // 200 < x ≤ 250
        { gt: 150, lte: 200, label: '151-200', color: '#069FC3' },   // 150 < x ≤ 200
        { gt: 100, lte: 150, label: '101-150', color: '#069FC3' },   // 100 < x ≤ 150
        { gt: 50, lte: 100, label: '51-100', color: '#00A2E7' },     // 50 < x ≤ 100
        { gt: 0, lte: 50, label: '1-50', color: '#1BB9FF' },         // 0 < x ≤ 50
        { value: 0, color: "#92D7EC", label: "0" }                   // x = 0
      ],
      // 人数统计1颜色分段（新增类型）
      baseColorPieces1: [
        { gt: 8000, label: '>8000', color: '#FBC606' },
        { gt: 7000, lte: 8000, label: '7001-8000', color: '#FBC606' },
        { gt: 6000, lte: 7000, label: '6001-7000', color: '#FEF104' },
        { gt: 5000, lte: 6000, label: '5001-6000', color: '#8FC320' },
        { gt: 4000, lte: 5000, label: '4001-5000', color: '#009B44' },
        { gt: 3000, lte: 4000, label: '3001-4000', color: '#069FC3' },
        { gt: 2000, lte: 3000, label: '2001-3000', color: '#069FC3' },
        { gt: 1000, lte: 2000, label: '1001-2000', color: '#00A2E7' },
        { gt: 0, lte: 1000, label: '1-1000', color: '#1BB9FF' },
        { value: 0, color: "#92D7EC", label: "0" }
      ],
      // 通过率颜色分段（新增类型）
      alternativeColorPieces: [
        { gte: 95.0, lte: 100.00, label: '95.0-100', color: '#0467B8' },
        { gte: 90.00, lt: 95.00, label: '90.0-94.9', color: '#0385D0' },
        { gte: 85.00, lt: 90.00, label: '85.0-89.9', color: '#019FE8' },//8
        { gte: 80.00, lt: 85.00, label: '80.0-84.9', color: '#0A9FBD' },
        { gte: 75.00, lt: 80.00, label: '75.0-79.9', color: '#079C98' },//6
        { gte: 70.00, lt: 75.00, label: '70.0-74.9', color: '#029B6C' },
        { gte: 65.00, lt: 70.00, label: '65.0-69.9', color: '#009D40' },//4
        { gte: 60.00, lt: 65.00, label: '60.0-64.9', color: '#23AE3B' },
        { gte: 40.00, lt: 60.00, label: '40.0-59.9', color: '#93C224' },
        { gte: 0.00, lt: 40.00, label: '0-39.9', color: '#CDDC07' }
      ],
      baseStyle: {
        areaColor: '#90c1fc',
        borderColor: 'rgba(49,93,254,0.1)',
        shadowColor: '#024bbe',
        shadowOffsetY: 15
      }
    };
  },
  watch: {
    currentMapCode(newVal) {
      this.handleMapChange(newVal, this.currentMap);
    },
    currentMap(newVal) {
      this.handleMapChange(this.currentMapCode, newVal);
    },
    mapData: {
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.updateMapWithData();
        }
      }
    },
    // 新增对type变化的监听
    type() {
      this.updateMapWithData();
    }
  },
  computed: {
    // 修改颜色分段逻辑，支持三种类型
    activeColorPieces() {
      switch(this.type) {
        case 'peoplecounting':
          return this.baseColorPieces;
        case 'peoplecounting1':
          return this.baseColorPieces1;
        case 'passrate':
          return this.alternativeColorPieces;
        default:
          return this.baseColorPieces;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
      if (this.currentMap && this.currentMapCode) {
        this.loadMap(this.currentMap, this.currentMapCode);
      }
      this.setupResizeObserver();
      this.addWindowResizeListener();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
    if (this.resizeDebounce) {
      clearTimeout(this.resizeDebounce);
      this.resizeDebounce = null;
    }
    this.removeWindowResizeListener();
  },
  methods: {
    handleMapChange(code, name) {
      const normalizedName = name === '全国' ? 'china' : name;
      if (code && normalizedName) {
        this.loadMap(normalizedName, code);
      }
    },

    initChart() {
      if (!this.$refs.map) return;
      try {
        this.chart = echarts.init(this.$refs.map);
        this.resizeChart();
      } catch (error) {
        console.error('ECharts初始化失败:', error);
      }
    },

    resizeChart() {
      if (this.resizeDebounce) {
        clearTimeout(this.resizeDebounce);
      }

      this.resizeDebounce = setTimeout(() => {
        if (this.chart) {
          this.chart.resize();
        }
        this.resizeDebounce = null;
      }, 200);
    },

    setupResizeObserver() {
      if (!this.$refs.mapContainer || !window.ResizeObserver) return;

      this.resizeObserver = new ResizeObserver(() => {
        this.resizeChart();
      });

      this.resizeObserver.observe(this.$refs.mapContainer);
    },

    addWindowResizeListener() {
      window.addEventListener('resize', this.resizeChart);
    },

    removeWindowResizeListener() {
      window.removeEventListener('resize', this.resizeChart);
    },

    async loadMap(mapName, mapCode) {
      if (!this.chart) return;

      try {
        let mapJson;
        if (mapCode === '000000') {
          mapJson = chinaJson;
        } else {
          try {
            mapJson = require(`@/assets/city/${mapCode}.json`);
          } catch (error) {
            console.error(`加载地图 ${mapCode}.json 失败:`, error);
            return;
          }
        }

        echarts.registerMap(mapName, mapJson);
        const data = this.prepareMapData(mapName, mapCode);
         let zoom = this.currentMapCode === '000000' ? '1.15' : '1';
        // let zoom = 1;
        this.chart.setOption({
          visualMap: {
            dimension: 0,
            textStyle: {
              color: '#fff'
            },
            pieces: this.activeColorPieces,
            left: '3%',
            bottom: '5%'
          },
          animation: false,
          geo: {
            zoom: zoom,
            roam: false,
            map: mapName,
            aspectScale: this.currentMapCode === '000000' ? 0.85 : 1,
            layoutCenter: ["50%", "50%"],
            layoutSize: '100%',
            itemStyle: {
              normal: {
                ...this.baseStyle,
                opacity: 1
              },
              emphasis: {
                areaColor: '#90c1fc'
              }
            },
            regions: [{
              name: '南海诸岛',
              itemStyle: {
                areaColor: 'rgb(0,243,255)',
                borderColor: 'rgb(0,243,255)',
                normal: {
                  opacity: 0,
                  label: {
                    show: false,
                    color: "#009cc9"
                  }
                }
              },
              label: {
                show: false
              }
            }]
          },
          tooltip: {
            trigger: 'item',
            className: 'custom-echarts-tooltip',
            backgroundColor: 'rgba(0, 0, 0, 0.85)',
            borderColor: 'rgba(255, 255, 255, 0.2)',
            borderWidth: 1,
            padding: [12, 16],
            textStyle: {
              fontSize: 14,
              color: '#fff',
              fontFamily: 'Arial, sans-serif',
              lineHeight: 22
            },
            extraCssText: 'box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); border-radius: 4px;',
            formatter: (params) => {
              if (!params.data) return '';

              // 根据类型显示不同的数值格式
              const value = this.type === 'passrate'
                ? `${params.data.value}`
                : params.data.value.toLocaleString();

              const colorIndicator = `<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${params.color};margin-right:6px"></span>`;

              return `
                <div style="margin-bottom:8px;font-weight:bold;font-size:16px;border-bottom:1px solid rgba(255,255,255,0.1);padding-bottom:6px">
                  ${params.name}
                </div>
                <div style="display:flex;align-items:center;margin:8px 0">
                  ${colorIndicator}
                  <span style="flex:1">总体：</span>
                  <span style="font-weight:bold;color:${ '#fff'}">
                    ${value}
                  </span>
                </div>
                <div style="margin-top:6px;font-size:12px;color:rgba(255,255,255,0.7);">
                  等级: ${this.getRangeLabel(params.data.value)}
                </div>
              `;
            }
          },
          series: [{
            type: 'map',
            map: mapName,
            zoom: zoom,
            roam: false,
            aspectScale:  this.currentMapCode === '000000' ? 0.85 : 1,
            layoutCenter: ["50%", "50%"],
            layoutSize: '100%',
            scaleLimit: {
              min: 1,
              max: 2
            },
            label: {
              normal: {
                show: true,
                textStyle: {
                  color: '#fff',
                  fontSize: 12,
                  textShadowColor: '#000',
                  textShadowBlur: 3
                }
              },
              emphasis: {
                textStyle: {
                  color: '#FFD700',
                  fontWeight: 'bold'
                }
              }
            },
            itemStyle: {
              normal: {
                areaColor: '#90c1fc',
                borderColor: 'rgba(49,93,254,0.4)',
                borderWidth: 2
              },
              emphasis: {
                areaColor: '#0160fa',
                borderWidth: 2,
                borderColor: '#00f6ff',
                shadowColor: 'rgate(0,246,255,0.8)',
                shadowBlur: 20
              }
            },
            data: data
          }]
        }, true);

        this.setupMapEvents(mapName, mapCode);
        this.resizeChart();
      } catch (error) {
        console.error('加载地图失败:', error);
      }
    },

    getRangeLabel(value) {
      const pieces = this.activeColorPieces;

      // 首先检查精确匹配
      const exactMatch = pieces.find(p => p.value !== undefined && value === p.value);
      if (exactMatch) return exactMatch.label;

      // 然后检查范围匹配
      for (const piece of pieces) {
        // 处理 gte 和 lte 的情况
        if (piece.gte !== undefined && piece.lte !== undefined) {
          if (value >= piece.gte && value <= piece.lte) {
            return piece.label;
          }
        }
        // 处理 gte 和 lt 的情况
        else if (piece.gte !== undefined && piece.lt !== undefined) {
          if (value >= piece.gte && value < piece.lt) {
            return piece.label;
          }
        }
        // 处理 gt 和 lte 的情况
        else if (piece.gt !== undefined && piece.lte !== undefined) {
          if (value > piece.gt && value <= piece.lte) {
            return piece.label;
          }
        }
        // 处理只有 gt 的情况
        else if (piece.gt !== undefined && piece.lte === undefined) {
          if (value > piece.gt) {
            return piece.label;
          }
        }
        // 处理只有 gte 的情况
        else if (piece.gte !== undefined && piece.lte === undefined) {
          if (value >= piece.gte) {
            return piece.label;
          }
        }
        // 处理只有 lte 的情况
        else if (piece.lte !== undefined && piece.gt === undefined) {
          if (value <= piece.lte) {
            return piece.label;
          }
        }
      }

      return '未知';
    },

    setupMapEvents(mapName, mapCode) {
      this.chart.off('click');
      this.chart.on('click', async(params) => {
        this.$emit('city-click', params.name);

        if (mapCode === '000000' && params.name !== '南海诸岛') {
          try {
            const provinceCode = params.data?.code || '';
            if (provinceCode) {
              this.$emit('update:currentMap', params.name);
              this.$emit('update:currentMapCode', provinceCode);
            }
          } catch (error) {
            console.error('下钻失败:', error);
          }
        }
      });

      this.chart.on('mouseover', params => {
        this.chart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          name: params.name
        });
      });

      this.chart.on('mouseout', params => {
        this.chart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          name: params.name
        });
      });
    },

    prepareMapData(mapName, mapCode) {
      return this.mapData.map(item => ({
        name: item.NAME,
        value: item.VALUE,
        code: item.CODE || ''
      }));
    },

    updateMapWithData() {
      if (!this.chart || !this.currentMap || !this.currentMapCode) return;

      const data = this.prepareMapData(this.currentMap, this.currentMapCode);
      this.chart.setOption({
        // 更新视觉映射配置（当类型变化时）
        visualMap: {
          pieces: this.activeColorPieces
        },
        series: [{
          data: data
        }]
      });

      this.resizeChart();
    }
  }
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;
  overflow: hidden;
  display: flex;
}

.map-chart {
  flex: 1;
  min-width: 0;
  min-height: 0;
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
}

@media (max-width: 768px) {
  .map-container {
    min-height: 300px;
  }

  .map-chart {
    min-height: 300px;
  }
}
</style>
